#include "widget.h"
#include <QPushButton>
#include <QHBoxLayout>
#include <QGroupBox>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{

    this->setMinimumSize(500, 500);
    // 创建表格视图和模型
    model = new QStandardItemModel(5, 2, this);
    for (int row = 0; row < model->rowCount(); ++row) {
        for (int col = 0; col < model->columnCount(); ++col) {
            model->setItem(row, col, new QStandardItem(QString("Item %1-%2").arg(row + 1).arg(col + 1)));
        }
    }
    tableView = new QTableView(this);
    tableView->setMinimumSize(300, 400);
    tableView->setModel(model);
    tableView->setSelectionBehavior(QAbstractItemView::SelectRows);

    // 创建按钮
    upButton = new QPushButton("Move Up", this);
    downButton = new QPushButton("Move Down", this);

    // 设置布局
    QVBoxLayout *mainlayout = new QVBoxLayout(this);
    mainlayout->setSpacing(10);
    mainlayout->setAlignment(Qt::AlignTop | Qt::AlignLeft);
    QVBoxLayout* vlayout = new QVBoxLayout(this);
    QHBoxLayout* hlayout = new QHBoxLayout(this);
    mainlayout->setSpacing(10);
    vlayout->addWidget(tableView);
    hlayout->addWidget(upButton);
    hlayout->addWidget(downButton);
    mainlayout->addLayout(vlayout);
    mainlayout->addLayout(hlayout);

    setLayout(mainlayout);

    // 连接按钮点击事件到槽函数
    connect(upButton, &QPushButton::clicked, this, &Widget::moveRowUp);
    connect(downButton, &QPushButton::clicked, this, &Widget::moveRowDown);
}

Widget::~Widget() {}

void Widget::moveRowUp()
{
    moveRow(-1);
}

void Widget::moveRowDown()
{
    moveRow(1);
}

void Widget::moveRow(int offset)
{

    QModelIndexList selectedIndexe = tableView->selectionModel()->selectedIndexes();
    if (selectedIndexe.isEmpty()) return;

    int row = selectedIndexe.first().row();
    int newRow = row + offset;

    // 检查新行是否有效
    //if (newRow < 0 || newRow >= model->rowCount()) return;
    newRow = newRow == -1 ? model->rowCount() - 1 : newRow;
    newRow = newRow == model->rowCount() ? 0 : newRow;

    // 交换行数据
    QList<QStandardItem*> oldRowItems = model->takeRow(row);
    //QList<QStandardItem*> newRowItems = model->takeRow(newRow);

    model->insertRow(newRow, oldRowItems);
    //model->insertRow(row, newRowItems);

    // 选择新的行
    tableView->clearSelection();
    tableView->selectRow(newRow);

    // 确保视图滚动到新的行位置
    tableView->scrollTo(model->index(newRow, 0));
}

